const router = require('koa-router')()
const { exec } = require('../db/index')
const jsonwebtoken = require('jsonwebtoken')
const { 
  getList,
  addUser,
  updateUser,
  deleteUser
 } = require('../model/users')


// 路由前缀
router.prefix('/api/users')


const auth = async (ctx, next) => {
  // console.log(ctx.request.header, 'heaader')  
  const { token = ''} = ctx.request.header;
   try {
    const user = jsonwebtoken.verify(token, 'helloworld')
    console.log(user, 'user')
    ctx.state.user = user
   } catch(err) {
    ctx.throw(401, err.message)
   }
  await next()
}


// 查询
router.get('/', async(ctx, next) => {
  const data = await getList()
  ctx.body = data
})

// 增加
router.post('/', async(ctx, next) => {
  const data = await addUser({...ctx.request.body})
  ctx.body = data.insertId || {}
})

// 修改
router.put('/:id', auth, async(ctx, next) => {
  const id = ctx.params.id;
  const data = await updateUser({id, ...ctx.request.body})
  ctx.body = data
})

// 删除
router.delete('/:id', async(ctx, next) => {
  const data = await deleteUser(ctx.params.id)
  ctx.body = data
})

router.post('/login', async(ctx, next) => {
  ctx.verifyParams({
    username: { type: "string",require: true },
    password: { type: 'string',require: true }
  })
  const sql = `select * from users where username='${ctx.request.body.username}' and password='${ctx.request.body.password}';`
  const userData = await exec(sql);

  if (!userData.length) {
    ctx.throw(401, 'username或者密码错误')
  }
  const { id, username, password } = userData;
  const token = jsonwebtoken.sign({id, username, password}, 'helloworld', {expiresIn: '48h'}) 
  ctx.body = { token }
})

module.exports = router
